/*
 * DoString.cpp
 *
 *  Created on: Oct 18, 2012
 *      Author: wtao
 */

#include "DoString.h"
#include <fstream>

DoString::DoString()
: _DoObject()
, mType(ePlain)
, mHexLiteral()
{
	mObjType = eString;
}

DoString::~DoString() 
{
}

std::string DoString::_debug_dump() const
{
	ostringstream oss;
	switch (mType) {
		case ePlain:
			oss << "\"" << mText << "\"";
			break;
		case eAscii85:
			break;
		case eHex:
			oss << setfill('0');
			const std::string &str = mHexLiteral.str();
			size_t len = str.size();
			if (str.size() > 6) {
				oss << "\"" << hex << setw(2) << (int)str[0] << setw(2) << (int)str[1] << setw(2) << (int)str[2];
				oss << " -" << dec << len << "- ";
				oss << hex << setw(2) << (int)str[len - 3] << setw(2) << (int)str[len - 2] << setw(2) << (int)str[len - 1];
				oss << "\"";
			} else {
				oss << "\"";
				for(size_t i = 0; i < len; i++) {
					oss << hex << setw(2) << (int)str[i];
				}
				oss << "\"";
			}
			break;
	}
	return oss.str();
}

void DoString::parseHex(std::string &str)
{
	if ((str.length() % 2) != 0) {
		str += '0';
	}
	size_t len = str.length() / 2;

	for(size_t i = 0; i < len; i++) {
		size_t pos = i * 2;
		std::string sub = str.substr(pos, 2);
		unsigned char b = (unsigned char)strtol(sub.c_str(), 0, 16);
		mHexLiteral.put(b);
	}
	mType = eHex;
}

void DoString::parseAscii85(std::string &str)
{
	mText = str;
	mType = eAscii85;
}

void DoString::_debug_hex(const std::string & path) const
{
	ofstream ofs(path, ios_base::trunc | ios_base::out | ios_base::binary);
	
	const std::string &str = mHexLiteral.str();
	ofs.write(str.data(), str.size());
	
	ofs.close();
}